const { mouse, straightTo, screen } = require("@nut-tree-fork/nut-js");
const screenshot = require('desktop-screenshot');
const Jimp = require('jimp');
const fs = require('fs');

async function getScreenResolution() {
    try {
        const width = await screen.width();
        const height = await screen.height();
        console.log(`📱 检测到屏幕分辨率: ${width} x ${height}`);
        return { width, height };
    } catch (error) {
        console.log('⚠️ nut.js 无法获取屏幕分辨率，使用默认值');
        return { width: 1920, height: 1080 };
    }
}

async function takeScreenshot() {
    try {
        console.log('📸 正在截取屏幕...');
        const screenshotPath = 'static/temp_screenshot.png';
        return new Promise((resolve, reject) => {
            screenshot(screenshotPath, (error, complete) => {
                if (error) {
                    reject(error);
                } else {
                    console.log('✅ 截图完成');
                    resolve(screenshotPath);
                }
            });
        });
    } catch (error) {
        console.error('截图失败:', error);
        throw error;
    }
}

async function findImageOnScreen(templatePath, confidence = 0.5) {
    try {
        console.log('📸 正在截取屏幕...');
        const screenshotPath = await takeScreenshot();
        
        console.log('🖼️ 正在加载模板图像...');
        console.log(`模板路径: ${templatePath}`);
        console.log(`截图路径: ${screenshotPath}`);
        
        // 检查文件是否存在
        if (!fs.existsSync(templatePath)) {
            throw new Error(`模板图片不存在: ${templatePath}`);
        }
        
        if (!fs.existsSync(screenshotPath)) {
            throw new Error(`截图文件不存在: ${screenshotPath}`);
        }
        
        // 获取文件信息
        const templateStats = fs.statSync(templatePath);
        const screenshotStats = fs.statSync(screenshotPath);
        
        console.log(`模板图片大小: ${templateStats.size} bytes`);
        console.log(`截图大小: ${screenshotStats.size} bytes`);
        
        // 获取实际屏幕分辨率
        const screenSize = await getScreenResolution();
        console.log(`🔄 屏幕分辨率: ${screenSize.width} x ${screenSize.height}`);
        
        // 实现真正的图像查找功能
        console.log('🔍 开始真正的图像查找...');
        
        // 使用 Jimp 进行图像匹配
        const result = await findImageWithJimp(templatePath, screenshotPath, confidence);
        
        if (result) {
            console.log(`🎯 找到目标图片，位置: (${result.x}, ${result.y})`);
            console.log(`📏 匹配度: ${(result.confidence * 100).toFixed(2)}%`);
            
            // 使用更精确的中心点计算
            const centerX = result.x + (result.width / 2);
            const centerY = result.y + (result.height / 2);
            
            // 四舍五入到最近的整数
            const roundedCenterX = Math.round(centerX);
            const roundedCenterY = Math.round(centerY);
            
            console.log(`🎯 图片中心点: (${roundedCenterX}, ${roundedCenterY})`);
            console.log(`📏 精确中心点: (${centerX.toFixed(2)}, ${centerY.toFixed(2)})`);
            
            return {
                x: result.x,
                y: result.y,
                width: result.width,
                height: result.height,
                center: {
                    x: roundedCenterX,
                    y: roundedCenterY
                }
            };
        }
        
        throw new Error('无法找到目标图片');
        
    } catch (error) {
        console.error('图像匹配失败:', error);
        throw error;
    }
}

async function findImageWithJimp(templatePath, screenshotPath, confidence = 0.5) {
    try {
        console.log('🔍 使用 Jimp 进行图像匹配...');
        
        // 加载模板图片和截图
        const templateImage = await Jimp.read(templatePath);
        const screenshotImage = await Jimp.read(screenshotPath);
        
        const templateWidth = templateImage.getWidth();
        const templateHeight = templateImage.getHeight();
        const screenshotWidth = screenshotImage.getWidth();
        const screenshotHeight = screenshotImage.getHeight();
        
        console.log(`📏 模板图片尺寸: ${templateWidth} x ${templateHeight}`);
        console.log(`📏 截图尺寸: ${screenshotWidth} x ${screenshotHeight}`);
        
        let bestMatch = {
            x: 0,
            y: 0,
            confidence: 0
        };
        
        // 使用更小的步长，提高匹配精度
        const stepSize = Math.max(1, Math.floor(Math.min(templateWidth, templateHeight) / 16));
        console.log(`🔍 搜索步长: ${stepSize} 像素 (提高精度)`);
        
        console.log('🔍 开始像素级图像匹配...');
        
        // 在截图中搜索模板图片
        for (let y = 0; y <= screenshotHeight - templateHeight; y += stepSize) {
            for (let x = 0; x <= screenshotWidth - templateWidth; x += stepSize) {
                let matchScore = 0;
                let totalPixels = 0;
                
                // 使用更小的采样步长，提高匹配精度
                const sampleStep = Math.max(1, Math.floor(Math.min(templateWidth, templateHeight) / 40));
                
                for (let ty = 0; ty < templateHeight; ty += sampleStep) {
                    for (let tx = 0; tx < templateWidth; tx += sampleStep) {
                        try {
                            const screenshotPixel = screenshotImage.getPixelColor(x + tx, y + ty);
                            const templatePixel = templateImage.getPixelColor(tx, ty);
                            
                            // 计算颜色差异
                            const screenRgb = Jimp.intToRGBA(screenshotPixel);
                            const templateRgb = Jimp.intToRGBA(templatePixel);
                            
                            const diff = Math.sqrt(
                                Math.pow(screenRgb.r - templateRgb.r, 2) +
                                Math.pow(screenRgb.g - templateRgb.g, 2) +
                                Math.pow(screenRgb.b - templateRgb.b, 2)
                            );
                            
                            // 使用颜色差异阈值判断匹配
                            if (diff < 80) { // 可以调整这个阈值
                                matchScore++;
                            }
                            totalPixels++;
                        } catch (pixelError) {
                            // 忽略边界像素错误
                            continue;
                        }
                    }
                }
                
                const currentConfidence = matchScore / totalPixels;
                
                if (currentConfidence > bestMatch.confidence) {
                    bestMatch = {
                        x: x,
                        y: y,
                        confidence: currentConfidence
                    };
                    // console.log(`🔍 发现更好的匹配: (${x}, ${y}) - 置信度: ${(currentConfidence * 100).toFixed(2)}%`);
                    
                    // 如果找到很好的匹配，提前退出
                    if (currentConfidence > 0.85) {
                        console.log('🎯 找到高置信度匹配，提前退出搜索');
                        break;
                    }
                }
            }
            
            // 如果找到很好的匹配，提前退出
            if (bestMatch.confidence > 0.85) {
                break;
            }
        }
        
        console.log(`🎯 最佳匹配置信度: ${(bestMatch.confidence * 100).toFixed(2)}%`);
        
        if (bestMatch.confidence >= confidence) {
            return {
                x: bestMatch.x,
                y: bestMatch.y,
                width: templateWidth,
                height: templateHeight,
                confidence: bestMatch.confidence
            };
        }
        
        console.log('❌ 未找到足够好的匹配');
        return null;
        
    } catch (error) {
        console.error('Jimp 图像匹配失败:', error);
        throw error;
    }
}

async function findRedBorderButton(imagePath) {
    try {
        console.log('🔍 正在查找红色边框按钮...');
        
        // 加载图片
        const image = await Jimp.read(imagePath);
        const width = image.getWidth();
        const height = image.getHeight();
        
        console.log(`📏 图片尺寸: ${width} x ${height}`);
        
        let redBorderRegions = [];
        
        // 扫描图片寻找红色边框，使用更精确的检测
        console.log('🔍 开始扫描红色像素...');
        let totalRedPixels = 0;
        
        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                try {
                    const pixel = image.getPixelColor(x, y);
                    const rgba = Jimp.intToRGBA(pixel);
                    
                    // 使用更精确的红色检测算法
                    const isRed = rgba.r > 140 && rgba.g < 120 && rgba.b < 120 && rgba.r > (rgba.g + rgba.b);
                    
                    if (isRed) {
                        totalRedPixels++;
                        // 检查周围是否有连续的红色像素形成边框
                        if (isRedBorderPixel(image, x, y, width, height)) {
                            redBorderRegions.push({ x, y, width: 1, height: 1 });
                        }
                    }
                } catch (pixelError) {
                    continue;
                }
            }
        }
        
        console.log(`🔍 检测到 ${totalRedPixels} 个红色像素`);
        
        if (redBorderRegions.length === 0) {
            console.log('❌ 未找到红色边框');
            return null;
        }
        
        // 合并相邻的红色像素区域
        const mergedRegions = mergeAdjacentRegions(redBorderRegions);
        
        // 找到最大的红色边框区域（通常是按钮）
        const largestRegion = findLargestRegion(mergedRegions);
        
        if (largestRegion) {
            console.log(`🎯 找到红色边框区域: (${largestRegion.x}, ${largestRegion.y}) - ${largestRegion.width} x ${largestRegion.height}`);
            
            // 使用预计算的中心点信息（如果可用）
            let centerX, centerY;
            if (largestRegion.centerX !== undefined) {
                centerX = largestRegion.preciseCenterX;
                centerY = largestRegion.preciseCenterY;
            } else {
                // 备用计算
                centerX = largestRegion.x + (largestRegion.width / 2);
                centerY = largestRegion.y + (largestRegion.height / 2);
            }
            
            // 四舍五入到最近的整数
            const roundedCenterX = Math.round(centerX);
            const roundedCenterY = Math.round(centerY);
            
            console.log(`🎯 按钮中心点位置: (${roundedCenterX}, ${roundedCenterY})`);
            console.log(`📏 精确中心点: (${centerX.toFixed(2)}, ${centerY.toFixed(2)})`);
            console.log(`📐 区域边界: [${largestRegion.x}, ${largestRegion.x + largestRegion.width}] x [${largestRegion.y}, ${largestRegion.y + largestRegion.height}]`);
            
            return {
                x: roundedCenterX,
                y: roundedCenterY,
                width: largestRegion.width,
                height: largestRegion.height,
                center: { x: roundedCenterX, y: roundedCenterY },
                preciseCenter: { x: centerX, y: centerY }
            };
        }
        
        return null;
        
    } catch (error) {
        console.error('红色边框检测失败:', error);
        throw error;
    }
}

function isRedBorderPixel(image, x, y, width, height) {
    try {
        // 检查周围8个方向是否有红色像素
        const directions = [
            [-1, -1], [-1, 0], [-1, 1],
            [0, -1],           [0, 1],
            [1, -1],  [1, 0],  [1, 1]
        ];
        
        let redNeighbors = 0;
        
        for (const [dx, dy] of directions) {
            const nx = x + dx;
            const ny = y + dy;
            
            if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
                try {
                    const neighborPixel = image.getPixelColor(nx, ny);
                    const neighborRgba = Jimp.intToRGBA(neighborPixel);
                    
                    // 使用相同的红色检测算法
                    const isRed = neighborRgba.r > 140 && neighborRgba.g < 120 && neighborRgba.b < 120 && neighborRgba.r > (neighborRgba.g + neighborRgba.b);
                    
                    if (isRed) {
                        redNeighbors++;
                    }
                } catch (e) {
                    continue;
                }
            }
        }
        
        // 如果周围有足够的红色像素，认为是边框的一部分
        // 降低阈值以提高检测精度
        return redNeighbors >= 2;
        
    } catch (error) {
        return false;
    }
}

function mergeAdjacentRegions(regions) {
    if (regions.length <= 1) return regions;
    
    const merged = [];
    const used = new Set();
    
    for (let i = 0; i < regions.length; i++) {
        if (used.has(i)) continue;
        
        let currentRegion = { ...regions[i] };
        used.add(i);
        
        // 查找相邻区域并合并
        for (let j = i + 1; j < regions.length; j++) {
            if (used.has(j)) continue;
            
            if (areRegionsAdjacent(currentRegion, regions[j])) {
                currentRegion = mergeTwoRegions(currentRegion, regions[j]);
                used.add(j);
            }
        }
        
        // 计算合并后区域的精确中心点
        const centerX = currentRegion.x + (currentRegion.width / 2);
        const centerY = currentRegion.y + (currentRegion.height / 2);
        
        // 四舍五入到最近的整数
        currentRegion.centerX = Math.round(centerX);
        currentRegion.centerY = Math.round(centerY);
        currentRegion.preciseCenterX = centerX;
        currentRegion.preciseCenterY = centerY;
        
        merged.push(currentRegion);
    }
    
    return merged;
}

function areRegionsAdjacent(region1, region2) {
    // 检查两个区域是否相邻
    const x1 = region1.x;
    const y1 = region1.y;
    const x2 = region2.x;
    const y2 = region2.y;
    
    // 水平相邻
    if (y1 === y2 && (x1 + region1.width === x2 || x2 + region2.width === x1)) {
        return true;
    }
    
    // 垂直相邻
    if (x1 === x2 && (y1 + region1.height === y2 || y2 + region2.height === y1)) {
        return true;
    }
    
    // 对角相邻
    if (Math.abs(x1 - x2) <= 1 && Math.abs(y1 - y2) <= 1) {
        return true;
    }
    
    return false;
}

function mergeTwoRegions(region1, region2) {
    const minX = Math.min(region1.x, region2.x);
    const minY = Math.min(region1.y, region2.y);
    const maxX = Math.max(region1.x + region1.width, region2.x + region2.width);
    const maxY = Math.max(region1.y + region1.height, region2.y + region2.height);
    
    return {
        x: minX,
        y: minY,
        width: maxX - minX,
        height: maxY - minY
    };
}

function findLargestRegion(regions) {
    if (regions.length === 0) return null;
    
    let largest = regions[0];
    let maxArea = largest.width * largest.height;
    
    for (const region of regions) {
        const area = region.width * region.height;
        if (area > maxArea) {
            maxArea = area;
            largest = region;
        }
    }
    
    // 确保返回的区域有中心点信息
    if (!largest.centerX) {
        const centerX = largest.x + (largest.width / 2);
        const centerY = largest.y + (largest.height / 2);
        largest.centerX = Math.round(centerX);
        largest.centerY = Math.round(centerY);
        largest.preciseCenterX = centerX;
        largest.preciseCenterY = centerY;
    }
    
    return largest;
}





// 主函数 - 支持多图片按顺序点击
async function main() {
    try {
        console.log('🎯 智能按钮点击工具 - 多图片模式');
        console.log('====================================');
        console.log('🔍 开始检测多个图片中的红色边框按钮...');
        await processMultipleImages();
    } catch (err) {
        console.error("❌ 程序执行失败:", err);
        process.exit(1);
    }
}



// 处理多个图片的函数
async function processMultipleImages() {
    try {
        console.log('🎯 多图片处理模式');
        console.log('==================');
        
        // 获取static文件夹中的所有PNG图片
        const imageFiles = await getImageFiles();
        
        if (imageFiles.length === 0) {
            console.log('❌ static文件夹中没有找到PNG图片文件');
            console.log('💡 请确保static文件夹中有名为 1.png, 2.png, 3.png... 的图片文件');
            process.exit(1);
        }
        
        console.log(`📁 找到 ${imageFiles.length} 个图片文件:`);
        imageFiles.forEach(file => console.log(`   - ${file}`));
        
        // 按顺序处理每个图片
        for (let i = 0; i < imageFiles.length; i++) {
            const imageFile = imageFiles[i];
            const imagePath = `static/${imageFile}`;
            
            console.log(`\n🔄 处理第 ${i + 1} 个图片: ${imageFile}`);
            console.log('=' + '='.repeat(30));
            
            try {
                await processSingleImage(imagePath, i + 1);
                console.log(`✅ 第 ${i + 1} 个图片处理完成`);
                
                // 如果不是最后一个图片，等待一下再处理下一个
                if (i < imageFiles.length - 1) {
                    console.log('⏳ 等待2秒后处理下一个图片...');
                    await new Promise(resolve => setTimeout(resolve, 2000));
                }
                
            } catch (error) {
                console.error(`❌ 处理第 ${i + 1} 个图片失败:`, error.message);
                console.log('⚠️ 继续处理下一个图片...');
            }
        }
        
        console.log('\n🎉 所有图片处理完成！');
        
    } catch (error) {
        console.error('❌ 多图片处理失败:', error.message);
        process.exit(1);
    }
}

// 获取static文件夹中的图片文件
async function getImageFiles() {
    try {
        const files = fs.readdirSync('static');
        const imageFiles = files
            .filter(file => file.toLowerCase().endsWith('.png'))
            .filter(file => /^\d+\.png$/.test(file)) // 只选择数字.png格式的文件
            .sort((a, b) => {
                // 按数字顺序排序
                const numA = parseInt(a.replace('.png', ''));
                const numB = parseInt(b.replace('.png', ''));
                return numA - numB;
            });
        
        return imageFiles;
    } catch (error) {
        console.error('❌ 读取static文件夹失败:', error.message);
        return [];
    }
}

// 处理单个图片
async function processSingleImage(imagePath, imageNumber) {
    try {
        console.log(`🔍 正在检测 ${imagePath} 中的红色边框按钮...`);
        const redButton = await findRedBorderButton(imagePath);
        
        if (redButton) {
            console.log('✅ 检测成功！');
            console.log(`📍 红色边框中心位置: (${redButton.x}, ${redButton.y})`);
            console.log(`📏 边框尺寸: ${redButton.width} x ${redButton.height}`);
            console.log(`🎯 中心点: (${redButton.x}, ${redButton.y})`);
            
            // 在屏幕上查找并点击
            console.log(`🔍 正在屏幕上查找 ${imagePath}...`);
            const imageLocation = await findImageOnScreen(imagePath, 0.6);
            
            if (imageLocation) {
                console.log("✅ 找到目标图片，位置:", imageLocation);
                
                // 计算按钮在屏幕上的绝对位置
                const buttonScreenX = imageLocation.x + redButton.x;
                const buttonScreenY = imageLocation.y + redButton.y;
                
                console.log(`🎯 按钮在屏幕上的位置: (${buttonScreenX}, ${buttonScreenY})`);
                console.log(`📍 相对偏移: (${redButton.x}, ${redButton.y})`);
                console.log(`🎯 点击中心点: (${buttonScreenX}, ${buttonScreenY})`);
                
                // 移动鼠标到按钮中心点位置并点击
                await mouse.move(straightTo({ x: buttonScreenX, y: buttonScreenY }));
                await mouse.leftClick();
                console.log(`✅ 第 ${imageNumber} 个图片的红色边框按钮中心点点击完成`);
                
            } else {
                console.log(`❌ 未找到 ${imagePath} 在屏幕上的位置`);
                throw new Error(`图片 ${imagePath} 在屏幕上未找到`);
            }
            
        } else {
            console.log('❌ 未检测到红色边框');
            throw new Error(`图片 ${imagePath} 中未检测到红色边框按钮`);
        }
        
    } catch (error) {
        console.error(`❌ 处理图片 ${imagePath} 失败:`, error.message);
        throw error;
    }
}

// 自动检测并点击红色边框按钮（保留用于单图片模式）
async function autoDetectAndClick() {
    try {
        console.log('🎯 自动检测模式');
        console.log('================');
        
        // 检查target.png是否存在
        const targetImage = 'static/target.png';
        if (!fs.existsSync(targetImage)) {
            console.log('❌ static/target.png 不存在，请确保文件存在');
            process.exit(1);
        }
        
        console.log('🔍 正在检测static/target.png中的红色边框按钮...');
        const redButton = await findRedBorderButton(targetImage);
        
        if (redButton) {
            console.log('✅ 检测成功！');
            console.log(`📍 红色边框中心位置: (${redButton.x}, ${redButton.y})`);
            console.log(`📏 边框尺寸: ${redButton.width} x ${redButton.height}`);
            console.log(`🎯 中心点: (${redButton.center.x}, ${redButton.center.y})`);
            
            // 在屏幕上查找并点击
            console.log('🔍 正在屏幕上查找static/target.png...');
            const imageLocation = await findImageOnScreen(targetImage, 0.6);
            
            if (imageLocation) {
                console.log("✅ 找到目标图片，位置:", imageLocation);
                
                // 计算按钮在屏幕上的绝对位置
                // redButton.x 和 redButton.y 已经是中心点坐标
                const buttonScreenX = imageLocation.x + redButton.x;
                const buttonScreenY = imageLocation.y + redButton.y;
                
                console.log(`🎯 按钮在屏幕上的位置: (${buttonScreenX}, ${buttonScreenY})`);
                console.log(`📍 相对偏移: (${redButton.x}, ${redButton.y})`);
                console.log(`🎯 点击中心点: (${buttonScreenX}, ${buttonScreenY})`);
                
                // 移动鼠标到按钮中心点位置并点击
                await mouse.move(straightTo({ x: buttonScreenX, y: buttonScreenY }));
                await mouse.leftClick();
                console.log("✅ 红色边框按钮中心点点击完成");
                
            } else {
                console.log("❌ 未找到static/target.png在屏幕上的位置");
                process.exit(1);
            }
            
        } else {
            console.log('❌ 未检测到红色边框');
            console.log('💡 提示：确保target.png中有明显的红色边框区域');
            process.exit(1);
        }
        
    } catch (error) {
        console.error('❌ 自动检测失败:', error.message);
        process.exit(1);
    }
}



// 执行主函数
main().catch(err => {
    console.error("❌ 程序执行失败:", err);
    process.exit(1);
});